import 'dart:io';

import 'package:app/pages/chat/chat_controller.dart';
import 'package:app/shared/constants/common.dart';
import 'package:flutter/material.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:get/get.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';

class ChatInputField extends StatefulWidget {
  ChatInputField({Key? key}) : super(key: key);

  @override
  _ChatInputFieldState createState() => _ChatInputFieldState();
}

class _ChatInputFieldState extends State<ChatInputField> {
  final ChatController _chatController = Get.find<ChatController>();
  final TextEditingController _controller = TextEditingController();
  bool emojiShowing = false;
  bool recordShowing = false;
  double offset = 0.0;

  //实例化对象
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  @override
  void initState() {
    super.initState();
    //    初始化
    recordPlugin.init();

    ///初始化方法的监听
    recordPlugin.responseFromInit.listen((data) {
      if (data) {
        print("初始化成功");
      } else {
        print("初始化失败");
      }
    });

    // 开始录制或结束录制的监听
    recordPlugin.response.listen((data) {
      if (data.msg == "onStop") {
        ///结束录制时会返回录制文件的地址方便上传服务器
        print("onStop  " + data.path!);
      } else if (data.msg == "onStart") {
        print("onStart --");
      }
    });

    //录制过程监听录制的声音的大小 方便做语音动画显示图片的样式
    recordPlugin.responseFromAmplitude.listen((data) {
      double num = double.parse(data.msg!);
      _chatController.updateDbLevel(num);
      // var voiceData = double.parse(data);

      // print("振幅大小   " + voiceData.toString());
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    recordPlugin.dispose();

    super.dispose();
  }

  void _handleStartRecord() {
    recordPlugin.start();
  }

  void _handleEndRecord() {
    recordPlugin.stop();
  }

  _onEmojiSelected(Emoji emoji) {
    _controller
      ..text += emoji.emoji
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _controller.text.length));
  }

  _onBackspacePressed() {
    _controller
      ..text = _controller.text.characters.skipLast(1).toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _controller.text.length));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
          vertical: sDefaultMarginPadding / 2,
          horizontal: sDefaultMarginPadding),
      decoration:
          BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor),
      child: SafeArea(
          child: Column(
        children: [
          Container(
            child: Row(
              children: [
                InkWell(
                  onTap: () {
                    setState(() {
                      recordShowing = !recordShowing;
                      emojiShowing = false;
                    });
                  },
                  child: Icon(
                    Icons.mic,
                    color: Colors.green,
                  ),
                ),
                SizedBox(
                  width: sDefaultMarginPadding,
                ),
                !recordShowing
                    ? Expanded(
                        child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: sDefaultMarginPadding * 0.75),
                        height: 50,
                        decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                  offset: Offset(0, 0),
                                  blurRadius: 32,
                                  color: Color(0xFF087949).withOpacity(0.1))
                            ],
                            color: Colors.green.withOpacity(0.05),
                            borderRadius: BorderRadius.circular(40)),
                        child: Row(
                          children: [
                            InkWell(
                              onTap: () {
                                setState(() {
                                  emojiShowing = !emojiShowing;
                                });
                              },
                              child:
                                  Icon(Icons.sentiment_satisfied_alt_outlined),
                            ),
                            SizedBox(
                              width: sDefaultMarginPadding / 2,
                            ),
                            Expanded(
                                child: TextField(
                              controller: _controller,
                              decoration: InputDecoration(
                                  hintText: "请输入", border: InputBorder.none),
                            )),
                            Icon(Icons.attach_file),
                            SizedBox(
                              width: sDefaultMarginPadding / 2,
                            ),
                            Icon(Icons.camera_alt_outlined)
                          ],
                        ),
                      ))
                    : GetBuilder(
                        init: _chatController,
                        builder: (controller) {
                          return Expanded(
                              child: GestureDetector(
                                  onLongPressStart: (detail) {
                                    _handleStartRecord();
                                    _chatController.startRecond();
                                  },
                                  onLongPressMoveUpdate: (details) {
                                    offset = details.localPosition.dy;
                                    if (offset < 0) {
                                      print("取消录音");
                                    }
                                  },
                                  onLongPressEnd: (detail) {
                                    _handleEndRecord();
                                    _chatController.endRecond();
                                  },
                                  child: Container(
                                    height: 50,
                                    decoration: BoxDecoration(
                                        color: Colors.green.withOpacity(
                                            _chatController.showLcp ? 0.5 : 1),
                                        borderRadius:
                                            BorderRadius.circular(40)),
                                    alignment: Alignment.center,
                                    child: Text(
                                      _chatController.showLcp ? "松开发送" : "按住说话",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  )));
                        })
              ],
            ),
          ),
          Offstage(
            offstage: !emojiShowing,
            child: SizedBox(
              height: 250,
              child: EmojiPicker(
                  onEmojiSelected: (Category category, Emoji emoji) {
                    _onEmojiSelected(emoji);
                  },
                  onBackspacePressed: _onBackspacePressed,
                  config: Config(
                      columns: 7,
                      // Issue: https://github.com/flutter/flutter/issues/28894
                      emojiSizeMax: 32 * (Platform.isIOS ? 1.30 : 1.0),
                      verticalSpacing: 0,
                      horizontalSpacing: 0,
                      initCategory: Category.RECENT,
                      bgColor: const Color(0xFFF2F2F2),
                      indicatorColor: Colors.blue,
                      iconColor: Colors.grey,
                      iconColorSelected: Colors.blue,
                      progressIndicatorColor: Colors.blue,
                      backspaceColor: Colors.blue,
                      showRecentsTab: true,
                      recentsLimit: 28,
                      noRecentsText: 'No Recents',
                      noRecentsStyle:
                          const TextStyle(fontSize: 20, color: Colors.black26),
                      tabIndicatorAnimDuration: kTabScrollDuration,
                      categoryIcons: const CategoryIcons(),
                      buttonMode: ButtonMode.MATERIAL)),
            ),
          ),
        ],
      )),
    );
  }
}
